package com.xijiekou.sifasuomax.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.xijiekou.sifasuomax.R;
import com.xijiekou.sifasuomax.adapter.NewOralAdapter;
import com.xijiekou.sifasuomax.bean.NewOralBean;
import com.xijiekou.sifasuomax.bean.NewWrittenBeans;
import com.xijiekou.sifasuomax.bean.PostRequestBean;
import com.xijiekou.sifasuomax.bean.SearchPartOneBean;
import com.xijiekou.sifasuomax.dialog.CommonDialog;
import com.xijiekou.sifasuomax.model.BaseModel;
import com.xijiekou.sifasuomax.model.NewWrittenModel;
import com.xijiekou.sifasuomax.model.PrintModel2;
import com.xijiekou.sifasuomax.model.SavePart1;
import com.xijiekou.sifasuomax.model.SearchPart1;
import com.xijiekou.sifasuomax.utils.BeanToJsonUtils;
import com.xijiekou.sifasuomax.utils.IntentUtils;
import com.xijiekou.sifasuomax.utils.SharePreferenceUtils;
import com.xijiekou.sifasuomax.utils.ToastUtils;
import com.xijiekou.sifasuomax.view.BottomConfirmView;
import com.xijiekou.sifasuomax.view.CommonVoiceEditTextView;
import com.xijiekou.sifasuomax.view.NoScrollListView;
import com.xijiekou.sifasuomax.view.SignNameView;
import com.xijiekou.sifasuomax.view.YearMonthDayView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * Created by zhouzhuo on 2017/7/27.
 * 3-3-1
 * 新建书面申请书
 */

public class NewWrittenActivity extends VoiceBaseActivity {
    private TextView tv_evidence_entering;
    private NoScrollListView listView;
    private ArrayList<NewOralBean> list;
    private NewOralAdapter adapter;
    private EditText et_file_name;
    private SignNameView signNameView;
    private CommonVoiceEditTextView rl_voice_one,rl_voice_two;
    private String caseId;
    private String search;
    private YearMonthDayView tv_ymd;
    private String fileNumber;
    private String fileName;
    private BottomConfirmView bottom_confirm_view;
    private TextView tv_add;
    private String audit;



    private MyHandler handler;
    private class  MyHandler extends Handler{
        private WeakReference<NewWrittenActivity> reference;
        public MyHandler(NewWrittenActivity activity){
            reference = new WeakReference<>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(reference.get()!=null){
                switch (msg.what){
                    case 0:
                        SearchPartOneBean one = (SearchPartOneBean) msg.obj;
                        fileName = one.filing;
                        setTextNotNull(fileName,et_file_name);
                        fileNumber = one.filenum;
                        rl_voice_one.setText(one.simple);
                        rl_voice_two.setText(one.content);
                        signNameView.setImage(one.signurl);
                        list = one.list;
                        if(list!=null &&list.size()>0){
                            setAdapter();
                        }
                        tv_ymd.setData(one.date);

                        break;
                }
            }
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_written);
        initView();
        handler = new MyHandler(this);
        caseId = getIntent().getStringExtra("caseId");
        search = getIntent().getStringExtra("search");
        audit = getIntent().getStringExtra("audit");
        initSearch();
    }

    private void initSearch() {
        SearchPart1 part = new SearchPart1();
        part.setCallBackListener(new BaseModel.CallBackListener<String>() {
            @Override
            public void success(String content) {
                try {
                    Log.d("zhouzhuo","查询=="+content);
                    JSONObject object = new JSONObject(content);
                    int code = object.getInt("code");
                    if(code == 1){
                        SearchPartOneBean one = new SearchPartOneBean();
                        JSONObject object1 = object.getJSONObject("data");
                        one.id = object1.getString("id");
                        one.case_id = object1.getString("case_id");
                        one.filing = object1.getString("filing");
                        one.simple = object1.getString("simple");
                        one.content = object1.getString("content");
                        one.source = object1.getString("source");
                        one.issuetype = object1.getString("issuetype");
                        one.signurl = object1.getString("signurl");
                        one.date = object1.getString("date");
                        one.filenum = object1.getString("filenum");
                        one.filename = object1.getString("filename");

                        try {
                            JSONArray array = object1.getJSONArray("persons");
                            if(array.length()>0){
                                Gson gson = new Gson();
                                ArrayList<NewOralBean> list =new ArrayList<>();
                                for (int i=0;i<array.length();i++){
                                    list.add(gson.fromJson(array.getJSONObject(i).toString(),NewOralBean.class));
                                }
                                one.list = list;
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                        Message message = Message.obtain();
                        message.what = 0;
                        message.obj = one;
                        handler.sendMessage(message);
                    }else if(code == 4012){
                        bottom_confirm_view.hidePrint();
                      //  ToastUtils.showShort(NewWrittenActivity.this,object.getString("data"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failed() {


            }
        });
        part.searchPart1(caseId);
    }




    private void initView() {
        tv_evidence_entering = (TextView) findViewById(R.id.tv_evidence_entering);
        tv_evidence_entering.setOnClickListener(this);
        listView = (NoScrollListView) findViewById(R.id.lv_list);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String type =list.get(position).type;
                switch (type){
                    case "1":
                        Intent intent1 = new Intent(NewWrittenActivity.this,AddOnePersonActivity.class);
                        intent1.putExtra("bean",list.get(position));
                        intent1.putExtra("position",position);
                        IntentUtils.startActivity(NewWrittenActivity.this,intent1,true,1);
                        break;
                    case "2":
                        intent1 = new Intent(NewWrittenActivity.this,AddTwoPersonActivity.class);
                        intent1.putExtra("bean",list.get(position));
                        intent1.putExtra("position",position);
                        IntentUtils.startActivity(NewWrittenActivity.this,intent1,true,2);
                        break;
                    case "3":
                        intent1 = new Intent(NewWrittenActivity.this,AddThreePersonActivity.class);
                        intent1.putExtra("bean",list.get(position));
                        intent1.putExtra("position",position);
                        IntentUtils.startActivity(NewWrittenActivity.this,intent1,true,3);
                        break;
                }
            }
        });
        listView.setDivider(getResources().getDrawable(R.drawable.new_oral_listview_divider));
        listView.setDividerHeight(15);
        et_file_name = (EditText) findViewById(R.id.et_file_name);
        rl_voice_one = (CommonVoiceEditTextView) findViewById(R.id.rl_voice_one);
        rl_voice_one.setNotice("纠纷简要情况:");
        rl_voice_two = (CommonVoiceEditTextView) findViewById(R.id.rl_voice_two);
        rl_voice_two.setNotice("当事人申请事项:");
        //ll_case_coming = (CaseComingView) findViewById(ll_case_coming);
        signNameView = (SignNameView) findViewById(R.id.tv_sign);
        signNameView.setSignTitle("申请人(签名盖章或按指纹)");
        tv_add = (TextView) findViewById(R.id.tv_add);
        tv_add.setOnClickListener(this);

        tv_ymd = (YearMonthDayView) findViewById(R.id.tv_ymd);

       // printView = (PrintView) findViewById(R.id.printView);
       // printView.setOnClickListener(this);
        bottom_confirm_view = (BottomConfirmView) findViewById(R.id.bottom_confirm_view);
        bottom_confirm_view.setSaveListener(new BottomConfirmView.SaveListener() {
            @Override
            public void save() {
                Log.d("zhouzhuo","执行save");
               /* NewWrittenBeans beans = getBeans();
                beans.isAudit = "1";
                saveAndCreate(beans);*/
            }
        });
        bottom_confirm_view.setConfirmListener(new BottomConfirmView.ConfirmListener() {
            @Override
            public void confirm() {
                Log.d("zhouzhuo","执行confirm");
                next();
            }
        });
        bottom_confirm_view.setPrintListener(new BottomConfirmView.PrintListener() {
            @Override
            public void print() {
                NewWrittenBeans beans = getBeans();
                String content = BeanToJsonUtils.get(beans);
                PrintModel2 model2 = new PrintModel2();
                model2.setCallBackListener(new BaseModel.CallBackListener<String>() {
                    @Override
                    public void success(String message) {
                        if(!TextUtils.isEmpty(message)&&message.equals("success")){
                            ToastUtils.showShort(NewWrittenActivity.this,"打印成功,请勿重复点击");
                        }else {
                            ToastUtils.showShort(NewWrittenActivity.this,"打印失败");
                        }

                    }

                    @Override
                    public void failed() {
                        ToastUtils.showShort(NewWrittenActivity.this,"打印失败,请检查打印服务是否开启");
                    }
                });
                String ip = (String) SharePreferenceUtils.get(NewWrittenActivity.this,"printIp","");
                if(TextUtils.isEmpty(ip)||ip.equals("1")){
                    ToastUtils.showShort(NewWrittenActivity.this,"暂不支持打印");
                }else {
                    model2.print(content,"printB1",ip);
                }

            }
        });


    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.tv_evidence_entering:
                Intent intent = new Intent(this,EvidenceEnteringActivity.class);
                intent.putExtra("id",caseId);
                IntentUtils.startActivity(NewWrittenActivity.this,intent);
                break;
            case R.id.tv_add:
                CommonDialog dialog = new CommonDialog(NewWrittenActivity.this);
                dialog.setListener(new CommonDialog.SelectTypeListener() {
                    @Override
                    public void click(int type) {
                        switch (type){
                            case 0:
                                Intent intent1 = new Intent(NewWrittenActivity.this,AddOnePersonActivity.class);
                                IntentUtils.startActivity(NewWrittenActivity.this,intent1,true,1);
                                break;
                            case 1:
                                intent1 = new Intent(NewWrittenActivity.this,AddTwoPersonActivity.class);
                                IntentUtils.startActivity(NewWrittenActivity.this,intent1,true,2);
                                break;
                            case 2:
                                intent1 = new Intent(NewWrittenActivity.this,AddThreePersonActivity.class);
                                IntentUtils.startActivity(NewWrittenActivity.this,intent1,true,3);
                                break;
                        }
                    }
                });
                dialog.show();
                break;

        }
    }
    private NewWrittenBeans getBeans(){
        NewWrittenBeans beans = new NewWrittenBeans();
        beans.case_id = caseId;
        beans.filing = et_file_name.getText().toString().trim();
        beans.simple = rl_voice_one.getVoiceContent();
        beans.content = rl_voice_two.getVoiceContent();
        // beans.source = ll_case_coming.getCurrentType()+"";
        // beans.issuetype = ll_case_coming.getDisputeType();
        beans.signurl = signNameView.getFilePath();
        beans.date = tv_ymd.getDate();
        beans.list = list;
        return beans;
    }

    private void saveAndCreate(NewWrittenBeans beans){
        //新建
        NewWrittenModel model = new NewWrittenModel(beans);
        model.setCallBackListener(new BaseModel.CallBackListener<String>() {
            @Override
            public void success(String message)  {
                if(!TextUtils.isEmpty(message.toString())){
                    try {
                        JSONObject object = new JSONObject(message);
                        ToastUtils.showLong(NewWrittenActivity.this,object.getString("data"));
                        if(object.getInt("code")==1){
                            Intent intent = getIntent();
                            setResult(0,intent);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void failed() {
                ToastUtils.showLong(NewWrittenActivity.this,"操作失败");
            }
        });
        model.postWritten();

    }



    //点击确认按钮
    private void next(){
        Log.d("zhouzhuo","执行next====");
        if(!TextUtils.isEmpty(audit)&&audit.equals("1")){
            ToastUtils.showShort(NewWrittenActivity.this,"审核已经通过，不能修改");
            return;
        }
        NewWrittenBeans beans = getBeans();
        if(TextUtils.isEmpty(search)){
            if(TextUtils.isEmpty(et_file_name.getText().toString().trim())){
                ToastUtils.showShort(NewWrittenActivity.this,"卷名不能为空");
                return;
            }
            saveAndCreate(beans);
        }else {
                SavePart1 savePart1 = new SavePart1(beans);
                savePart1.setCallBackListener(new BaseModel.CallBackListener<PostRequestBean>() {
                    @Override
                    public void success(PostRequestBean message) {
                        ToastUtils.showLong(NewWrittenActivity.this,message.data);
                        if(message.code==1){
                            Intent intent = getIntent();
                            setResult(1,intent);
                            finish();
                        }
                    }

                    @Override
                    public void failed() {

                    }
                });
                savePart1.postWritten();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data == null){
            return;
        }
        switch (requestCode){
            case 1:
                switch (resultCode){
                    case 1:
                        NewOralBean bean = (NewOralBean) data.getSerializableExtra("bean");
                        bean.type = "1";
                        updateList(bean);
                        break;
                    case 10:
                        bean = (NewOralBean) data.getSerializableExtra("bean");
                        int position = data.getIntExtra("position",-1);
                        if(position!=-1){
                            update(position,bean);
                        }
                        break;
                }
                break;
            case 2:
                switch (resultCode){
                    case 2:
                        NewOralBean bean = (NewOralBean) data.getSerializableExtra("bean");
                        bean.type = "2";
                        updateList(bean);
                        break;
                    case 20:
                        bean = (NewOralBean) data.getSerializableExtra("bean");
                        int position = data.getIntExtra("position",-1);
                        if(position!=-1){
                            update(position,bean);
                        }
                        break;
                }

                break;
            case 3:
                switch (resultCode){
                    case 3:
                        NewOralBean bean = (NewOralBean) data.getSerializableExtra("bean");
                        bean.type = "3";
                        updateList(bean);
                        break;
                    case 30:
                        bean = (NewOralBean) data.getSerializableExtra("bean");
                        int position = data.getIntExtra("position",-1);
                        if(position!=-1){
                            update(position,bean);
                        }
                        break;
                }
                break;
        }
    }

    private void updateList(NewOralBean bean) {
        if(list == null){
            list = new ArrayList<>();
        }
        list.add(bean);
        setAdapter();
    }

    public void setAdapter(){
        adapter = new NewOralAdapter(this,list);
        listView.setAdapter(adapter);
    }

    private void update(int position,NewOralBean bean){
        list.remove(position);
        list.add(position,bean);
        NewOralAdapter  adapter = new NewOralAdapter(this,list);
        listView.setAdapter(adapter);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(handler!=null){
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }
}
